package common

import (
	"encoding/json"
	"os"

	"github.com/taoshihan1991/imaptool/tools"
)

const (
	DefaultServer   = "127.0.0.1"
	DefaultPort     = "3306"
	DefaultDatabase = "kefu"
	DefaultUsername = "kefu"
	DefaultPassword = "4irzGPZzSJwiSPMG"
)

type Mysql struct {
	Server   string
	Port     string
	Database string
	Username string
	Password string
}

func GetMysqlConf() *Mysql {
	var mysql = &Mysql{}
	isExist, err := tools.IsFileExist(MysqlConf)
	if err != nil {
		// 如果发生错误，返回带有默认值的配置
		return getDefaultMysqlConf()
	}
	if !isExist {
		// 如果配置文件不存在，返回带有默认值的配置
		return getDefaultMysqlConf()
	}
	info, err := os.ReadFile(MysqlConf)
	if err != nil {
		// 如果读取文件错误，返回带有默认值的配置
		return getDefaultMysqlConf()
	}
	err = json.Unmarshal(info, mysql)
	if err != nil {
		// 如果解析配置错误，返回带有默认值的配置
		return getDefaultMysqlConf()
	}
	return mysql
}

// getDefaultMysqlConf 返回带有默认值的 Mysql 配置
func getDefaultMysqlConf() *Mysql {
	return &Mysql{
		Server:   DefaultServer,
		Port:     DefaultPort,
		Database: DefaultDatabase,
		Username: DefaultUsername,
		Password: DefaultPassword,
	}
}
